package com.fingard.dsp.bank.directbank.cqsx01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;
//import java.util.Objects;

/**
 * @author: liuxb
 * @create: 2020-05-17 13:45
 * @version: 1.0
 **/
public class CQSX01BatPayRec extends CQSX01Base implements IBatPayRec {
    /**
     * 批量代发提交
     *
     * @param p_req1988 批量代付请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try {
            //======拼接报文======
            //拼接请求报文体
            CQSX01Header header = new CQSX01Header();
//                if(p_req1988.readedDetail.sameBnk.equals("1")){//同行标志 (1：同行,   0：他行)
            if ("198801".equals(p_req1988.reqHeader.commandCode)) {//代发工资
                header.transCode = "B2EPayRoll";//银行交易码
            } else if ("198802".equals(p_req1988.reqHeader.commandCode)) {//批量转账
                header.transCode = "B2ECrossBatchTransfer";//银行交易码
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "无法区分指令是198801还是198802";
                WriteBankLogLn("无法区分指令是198801还是198802");
                retAts.writeRetToATS();
                return retAts;
            }
            header.ERPJnlNo = p_req1988.reqHeader.transSeqID;//生成交易流水号
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入CQSX01通用的头部节点
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            xmlWriter.writeStartElement("Message");
            xmlWriter.writeStartElement("Head");
            xmlWriter.writeElementString("TrsCode", header.transCode);//银行交易码，用以区分不同的操作
            Date tmpDateNow = new Date();
            xmlWriter.writeElementString("ERPTrsTimestamp", Format.DateTimeFormat.format(tmpDateNow));//交易时间(格式为：yyyy-MM-dd HH:mm:ss)
            xmlWriter.writeElementString("ERPJnlNo", header.ERPJnlNo);//ERP（财务系统）交易流水号
            xmlWriter.writeEndElement();

            xmlWriter.writeStartElement("Body");
            xmlWriter.writeStartElement("List");
            xmlWriter.writeStartElement("Map");
            xmlWriter.writeElementString("AcctNo", p_req1988.ownAct);//付款账号
            if ("198801".equals(p_req1988.reqHeader.commandCode)) {//
                xmlWriter.writeElementString("AcctName", p_req1988.ownActName);//付款账户户名
                xmlWriter.writeElementString("Remark", p_req1988.payType, true);//摘要，用途（交易类型）
            } else {//
                xmlWriter.writeElementString("TotalNum", p_req1988.totalNum);//总笔数
                xmlWriter.writeElementString("TotalAmt", p_req1988.totalAmt);//总金额
            }
            xmlWriter.writeStartElement("List");
            while (p_req1988.readRecord()) {
                xmlWriter.writeStartElement("Map");
//                xmlWriter.writeElementString("Number", Format.Time9Format.format(new Date()));//唯一支付批号
                xmlWriter.writeElementString("Number", Format.Time9Format.format(new Date()) + new TransIDHelper(1, 9).getNextIDStr());//唯一支付批号
                xmlWriter.writeElementString("RcvAcct", p_req1988.readedDetail.recAct);//收款账号
                xmlWriter.writeElementString("RcvAcctName", p_req1988.readedDetail.recName);//对方账户户名
                if ("198801".equals(p_req1988.reqHeader.commandCode)) {//代发工资
                    xmlWriter.writeElementString("TranAmt", p_req1988.readedDetail.payAmount);//金额
                    xmlWriter.writeElementString("PostScript", p_req1988.readedDetail.memo);//附言
                    xmlWriter.writeElementString("TranUsage", p_req1988.readedDetail.purpose, true);//转账用途(ATS将用途写在备注)
                } else {//批量转账
                    if ("1".equals(p_req1988.readedDetail.sameBnk)) {//同行标志 (1：同行,   0：他行)
                        xmlWriter.writeElementString("RcvBankType", "0");//收款方银行类别 0：行内 1：行外
                    } else {
                        xmlWriter.writeElementString("RcvBankType", "1");//收款方银行类别 0：行内 1：行外
                    }
                    xmlWriter.writeElementString("TranAmt", p_req1988.readedDetail.payAmount);//金额
//                    xmlWriter.writeElementString("TranUsage", p_req1988.readedDetail.useType);//转账用途
                    xmlWriter.writeElementString("TranUsage", p_req1988.readedDetail.purpose, true);//转账用途(ATS将用途写在备注)
//                    xmlWriter.writeElementString("TranUsage", p_req1988.useType,true);//转账用途
                    xmlWriter.writeElementString("RcvBankJionNo", p_req1988.readedDetail.cnapsCode, true);//收款方银行联行号
                }
                xmlWriter.writeElementString("ReservedField1", p_req1988.readedDetail.askNumber, true);//对账码
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

// 发送给银行获得应答报文
            String[] retStrArr = sendToBank(xmlWriter.toXmlString(), p_req1988.reqHeader.transType, p_req1988.reqHeader.commandCode, header.transCode);

            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(tmpRetCode)) {
                        String ReturnCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                        String ReturnMsg = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_req1988.reqBatchNO;
                        retAts.respInfo = ReturnCode + "+" + ReturnMsg;
                        retAts.transState = ReturnCode;
                        retAts.payInfoCode = retAts.transState;
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(retStrArr[1].toString());
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常：" + e);
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代付状态查询
     *
     * @param p_req1998 批量代付查询请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
//            retAts.writeStart();
        try {
            retAts.reqSeqID = p_req1998.reqBatchNO;
            CQSX01Header tmpBnkHeader = new CQSX01Header();
            if ("198801".equals(p_req1998.reqHeader.commandCode)) {
                tmpBnkHeader.transCode = "B2EPayRollDetailQry";//银行交易码
            } else if ("198802".equals(p_req1998.reqHeader.commandCode)) {
                tmpBnkHeader.transCode = "B2EBatchTransferDetailQry";//银行交易码
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "无法区分指令是198801还是198802";
                WriteBankLogLn("无法区分指令是198801还是198802");
                retAts.writeAfterDetail();
                return retAts;
            }
            tmpBnkHeader.ERPTrsTimestamp = p_req1998.reqHeader.transTime;//指令请求时间
            tmpBnkHeader.ERPJnlNo = p_req1998.reqHeader.transSeqID;//生成交易流水号
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入CQSX01通用的头部节点
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            xmlWriter.writeStartElement("Message");
            xmlWriter.writeStartElement("Head");
            xmlWriter.writeElementString("TrsCode", tmpBnkHeader.transCode);//银行交易码，用以区分不同的操作
            Date tmpDateNow = new Date();
            xmlWriter.writeElementString("ERPTrsTimestamp", Format.DateTimeFormat.format(tmpDateNow));//交易时间(格式为：yyyy-MM-dd HH:mm:ss)
            xmlWriter.writeElementString("ERPJnlNo", tmpBnkHeader.ERPJnlNo);//ERP（财务系统）交易流水号
            xmlWriter.writeEndElement();

            xmlWriter.writeStartElement("Body");
            xmlWriter.writeStartElement("List");
            xmlWriter.writeStartElement("Map");
            xmlWriter.writeElementString("BatchNo", p_req1998.reqBatchNO);//批次号
            xmlWriter.writeElementString("AcctNo", p_req1998.ownAct);//付款账号
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成

            // 发送给银行获得应答报文
            String[] resultBank = sendToBank(xmlWriter.toXmlString(), p_req1998.reqHeader.transType, p_req1998.reqHeader.commandCode, tmpBnkHeader.transCode);

            if (resultBank[0].length() == 0) {// 成功响应
                StringBuilder tmpSbMsg = new StringBuilder();//存提示信息
                XmlTextReader tmpBkReader = loadBankRespXmlReader(resultBank[1], tmpSbMsg);// 把银行返回报文转成XmlTextReader格式
                if (tmpBkReader != null) {// 返回报文的内容不为空
                    String IBSReturnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String IBSReturnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(IBSReturnCode)) {
                        String ReturnCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                        String ReturnMsg = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                        if ("000000".equals(ReturnCode)) {
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.respInfo = ReturnMsg;
                            retAts.writeBeforeDetail();
                            while (tmpBkReader.read("/Message/Body/List/Map/List/Map")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleTextNotNull("ReservedField1").trim();//对账码
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleTextNotNull("RcvAcct").trim();//收款账号
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleTextNotNull("RcvAcctName").trim();//收款账户户名
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleTextNotNull("TranAmt").trim();//金额
                                tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleTextNotNull("TranUsage").trim();//转账用途
                                tmpRetDetail.result = tmpBkReader.readedXElement.getSingleTextNotNull("TranStatus").trim();//交易状态
                                tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleTextNotNull("TranRspMsg").trim();//失败原因
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;//处理代码
                                tmpRetDetail.payAct = p_req1998.ownAct;//支付帐号
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo(ReturnMsg);
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.transState = ReturnCode;//交易状态
                            retAts.payInfoCode = retAts.transState;
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(IBSReturnMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(resultBank[1].toString());
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    /**
     * 批量代扣提交
     *
     * @param p_req9188 批量代扣请求对象
     * @return 批量代扣响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    /**
     * 批量代收状态查询
     *
     * @param p_req9198 批量代扣查询请求对象
     * @return 批量代扣查询响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}

